import { EzFormConfiguration } from '../components/ez-form';
import { EzFormControlConfiguration } from '../components/ez-form-control';
import { EzFormGroupConfiguration } from '../components/ez-form-group';

const getDuplicateElements: <T = any>(elements: T[]) => T[] = elements => {
  const duplicated = [];
  if (elements.length >= 2) {
    elements.forEach(e => {
      if (elements.filter(item => item === e).length > 1) {
        if (!duplicated.includes(e)) {
          duplicated.push(e);
        }
      }
    });
  }
  return duplicated;
};

export class EzFormConfigurationValidator {
  static validateControl(configuration: EzFormControlConfiguration): void {
    if (!configuration || !configuration.type || !configuration.name) {
      throw new Error(`表单控件[${configuration && configuration.name ? configuration.name : '未知名称'}]配置不正确`);
    }
  }

  static validateGroup(configuration: EzFormGroupConfiguration): void {
    if (!configuration || !configuration.name || !configuration.controls) {
      throw new Error(`表单控件组[${configuration && configuration.name ? configuration.name : '未知名称'}]配置不正确`);
    }
    const names: string[] = configuration.controls.map(item => item.name);
    const duplicatedNames = getDuplicateElements(names);
    if (duplicatedNames.length > 0) {
      throw new Error(`控件名称[${duplicatedNames.join(',')}]重复`);
    }
    configuration.controls.forEach(c => this.validateControl(c));
  }

  static validateForm(configuration: EzFormConfiguration): void {
    if (!configuration || !configuration.groups) {
      throw new Error(`表单配置不正确`);
    }
    const groupNames = configuration.groups.map(g => g.name);
    const duplicatedNames = getDuplicateElements(groupNames);
    if (duplicatedNames.length > 0) {
      throw new Error(`控件组名称[${duplicatedNames.join(',')}]重复`);
    }
    configuration.groups.forEach(c => this.validateGroup(c));
  }
}
